<template>
  <div>

    <el-drawer
      custom-class="drawer_box"
      :size="custShow.width"
      :title="custShow.title"
      v-model="custShow.visible"
      @close="handleClose"
      ref="DrawerRef"
    >
      <ZwSearchForm
        row-num="3"
        :option="searchOption"
        @search="search"
        @reset="reset"
        ref="searchRef"
      ></ZwSearchForm>
      <el-scrollbar class="scrollbar">
        <ZwTable
          ref="tableRef"
          class="table-box"
          :option="tableOption"
          :fetch-params="state.searchParams"
          :fetch-api="getData()"
        >
          <template #headerOperate>
            <el-checkbox
              @change="changeOverdue"
              v-model="is_overdue"
              label="已逾期"
            ></el-checkbox>
            <el-checkbox
              @change="changeAudit"
              v-model="is_audit"
              label="未审核"
            ></el-checkbox>
          </template>
        </ZwTable>
      </el-scrollbar>
    </el-drawer>
  </div>

  <!--详情-->
  <objectDetail
    ref="objectRef"
    @refresh="reset"
  ></objectDetail>
</template>
<script lang="tsx" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElButton, ElMessage, ElPopover, ElProgress } from 'element-plus'
import ZwSearchForm from '@/components/zw/search-form/SearchForm'
import ZwTable from '@/components/zw/table/Table'
import objectDetail from './objectDetail.vue'
import { workUserDetail, taskRemind, execCyle } from '@/api/employe/employeetasks/taskmanage'
import { stageList } from '@/api/customerCenter/labellagroup'
import { gradeList } from '@/api/customer/clubManage/clueGrade'
import { deepCopy } from '@/utils/helper'
const DrawerRef = ref(null)
const objectRef = ref(null)
const searchRef = ref(null)
const is_overdue = ref(false)
const is_audit = ref(false)
const obj_type = ref()
const list = ref()
const formData = reactive({
  type: '',
  cust_name: '',
  task_type: '',
  task_id: '',
  is_detail: 1,
  showExamine: 0
})
const defaultParams = reactive({
  task_id: '',
  work_user_id: '',
  call_result: -1,
  cust_stage: -1,
  exec_cycle: [],
  nameornickname: '',
  phone: '',
  complete_time: [],
  is_overdue: 1,
  is_audit: 1,
  flow: -1
})
const state = reactive({
  searchParams: deepCopy(defaultParams)
})
const searchOption = ref([
  {
    label: '沟通结果',
    name: 'call_result',
    value: '',
    type: 'select',
    placeholder: '全部',
    fetchOptionApi: () => {
      return new Promise((resolve) => {
        resolve([
          {
            name: '全部',
            id: -1
          },
          {
            name: '已接通',
            id: 1
          },
          {
            name: '未接通',
            id: 2
          },
          {
            name: '挂断',
            id: 3
          },
          {
            name: '空号',
            id: 4
          },
          {
            name: '未联系',
            id: 0
          }
        ])
      })
    },
    formatOption: (v) => ({
      label: v.name,
      value: v.id
    })
  },
  {
    label: '客户评级',
    name: 'cust_stage',
    value: '',
    type: 'select',
    placeholder: '全部',
    fetchOptionApi: () => {
      return new Promise((resolve) => {
        resolve(list.value)
      })
    },
    formatOption: (v) => ({
      label: v.name,
      value: v.id
    })
  },
  {
    label: '执行周期',
    name: 'exec_cycle',
    value: [],
    type: 'datePicker',
    datePickerType: 'daterange',
    datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
    valueFormat: 'YYYY-MM-DD HH:mm:ss',
    startPlaceholder: '开始时间',
    endPlaceholder: '结束时间',
    popperClass: 'create_time'
  },
  {
    label: '客户信息',
    name: 'nameornickname',
    value: '',
    type: 'input',
    placeholder: '请输入客户姓名/昵称'
  },
  {
    label: '客户手机',
    name: 'phone',
    value: '',
    type: 'input',
    placeholder: '请输入客户手机'
  },
  {
    label: '完成时间',
    name: 'complete_time',
    value: [],
    type: 'datePicker',
    datePickerType: 'daterange',
    datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
    valueFormat: 'YYYY-MM-DD HH:mm:ss',
    startPlaceholder: '开始时间',
    endPlaceholder: '结束时间',
    popperClass: 'create_time'
  }
])
const custShow = reactive({})
const tableOption = reactive([
  {
    prop: 'name',
    label: '客户信息',
    width: 280,
    render({ row, column, index }) {
      return (
        <div>
          <el-avatar style="width: 40px; height:40px; vertical-align: middle; margin-right: 10px" shape="square" src={row.avatar ? row.avatar : '/static/user.png'}></el-avatar>
          <span>{row.name}</span>
          <span v-show={row.nickname}>{'(' + row.nickname + ')'}</span>
          <el-image style="width: 14px; height: 14px" src={row.sex == 2 ? '/static/employeetasks/female.png' : row.sex == 0 ? '/static/employeetasks/noSex.png' : '/static/employeetasks/male.png'}></el-image>
        </div>
      )
    }
  },
  {
    prop: 'phone',
    label: '手机号',
    width: 150
  },
  {
    prop: 'call_result',
    label: '沟通结果',
    width: 100
  },
  {
    prop: 'cust_stage_name',
    label: '客户评级',
    width: 100
  },
  {
    prop: 'remark',
    label: '备注',
    width: 200
  },
  {
    prop: 'complete_time',
    label: '完成时间',
    width: 200
  },
  {
    prop: 'audit_status_name',
    label: '审核状态',
    width: 150
  },
  {
    prop: 'operate',
    label: '操作',
    width: 260,
    fixed: 'right',
    isOperate: true,
    render({ row, column, index }) {
      return (
        <div>
          <ElButton
            class="sopBtn"
            onClick={() => {
              toExamine(row, 0)
            }}
          >
            查看详情
          </ElButton>
          <ElButton
            v-show={row.audit_status == 1 && row.status == 2 && row.is_auth == 2}
            class="sopBtn"
            onClick={() => {
              toExamine(row, 1)
            }}
          >
            审核
          </ElButton>
          <ElButton
            class="sopBtn"
            v-show={!row.complete_time}
            onClick={() => {
              custRemind(row)
            }}
          >
            提醒
          </ElButton>
        </div>
      )
    }
  }
])
const toExamine = (val: any, type: any) => {
  formData.showExamine = type
  objectRef.value.openObject(formData, val)
}
const custRemind = (val: any) => {
  const params = {
    type: 2,
    task_id: state.searchParams.task_id,
    work_user_id: state.searchParams.work_user_id,
    object_id: val.object_id
  }
  taskRemind(params).then((res: any) => {
    ElMessage.success('提醒已发送')
  })
}
const changeOverdue = (val: any) => {
  val ? (defaultParams.is_overdue = 2) : (defaultParams.is_overdue = 1)
  search()
}
const changeAudit = (val: any) => {
  val ? (defaultParams.is_audit = 2) : (defaultParams.is_audit = 1)
  search()
}
const openCust = (val: any, data: any) => {
  console.log(val, data, 'aa')
  obj_type.value = data.object_type
  if (data.object_type == 1) {
    tableOption[3].label = '线索评级'
    searchOption.value[1].label = '线索评级'
    gradeList({ page: 1, page_size: 99999 }).then((r: any) => {
      list.value = r.data
    })
  } else {
    stageList({ page: 1, page_size: 99999 }).then((res: any) => {
      list.value = res
      list.value.unshift({
        name: '全部',
        id: -1
      })
    })
    searchOption.value[1].label = '客户评级'
    tableOption[3].label = '客户评级'
  }
  state.searchParams.task_id = data.task_id
  state.searchParams.work_user_id = val.work_user_id
  custShow.title = `【${data.name}】${val.name}的执行详情`
  custShow.visible = true
  custShow.width = 1100
  formData.type = data.name
  formData.cust_name = val.name
  formData.cust_type = data.type
  formData.task_id = data.task_id
  if (data.type == 3) {
    tableOption[2] = {
      prop: 'cust_info',
      label: '客户微信号|企业微信号',
      width: 170,
      render({ row, column, index }) {
        if (row.cust_info) {
          return (
            <div style="display:flex">
              {row.cust_info.map((item: any, index: any) => {
                return (
                  <div>
                    {item.name}
                    <span style={item.corp_name ? 'color: #ff6b00;' : 'color: #59d2a0;'}>{item.corp_name ? item.corp_name + ' ' : '@微信 '}</span>
                  </div>
                )
              })}
            </div>
          )
        }
      }
    }
    searchOption.value[0] = {
      label: '任务进度',
      name: 'flow',
      value: '',
      type: 'select',
      placeholder: '全部',
      fetchOptionApi: () => {
        return new Promise((resolve) => {
          resolve([
            {
              name: '未开始',
              id: 1
            },
            {
              name: '已加微',
              id: 2
            },
            {
              name: '已跟进',
              id: 3
            },
            {
              name: '客户评级',
              id: 4
            },
            {
              name: '已完成',
              id: 5
            }
          ])
        })
      },
      formatOption: (v) => ({
        label: v.name,
        value: v.id
      })
    }
  }
  if (data.type == 2) {
    tableOption[2] = {
      prop: 'current_progress',
      label: '任务进度',
      width: 450,
      render({ row, column, index }) {
        var arr = []
        for (let i in row.progress_list) {
          arr.push({index:i,name:row.progress_list[i]})
        }
        return (
          <div style="display:flex;">
            {arr.map((item: any, index: any) => {
              return (
                <div style={index + 1 == arr.length ? '' : 'border-top:1px dashed #FFC69E;'} style="position:reative;line-height:35px;padding-right:15px">
                  <div style={item.index < row.current_progress ? 'border:2px solid #FF6B00' : 'border:2px solid #D8D8D8'} style="width:8px;height:8px;border-radius:50%;position:absolute;top:11px"></div>
                  <div style={row.current_progress == item.index ? 'color:#FF6B00' : item.index < row.current_progress ? 'color:#33302D' : 'color:#969696'}>{item.name}</div>
                </div>
              )
            })}
          </div>
        )
      }
    }
    searchOption.value[0] = {
      label: '任务进度',
      name: 'flow',
      value: '',
      type: 'select',
      placeholder: '全部',
      fetchOptionApi: () => {
        return new Promise((resolve) => {
          resolve([
            {
              name: '全部',
              id: -1
            },
            {
              name: '未开始',
              id: 1
            },
            {
              name: '计划拜访',
              id: 2
            },
            {
              name: '已签到',
              id: 3
            },
            {
              name: '已跟进',
              id: 4
            },
            {
              name: '客户评级',
              id: 5
            },
            {
              name: '已完成',
              id: 6
            }
          ])
        })
      },
      formatOption: (v) => ({
        label: v.name,
        value: v.id
      })
    }
  }
  if (data.type == 1) {
    tableOption[2] = {
      prop: 'call_result',
      label: '沟通结果',
      width: 100
    }
    searchOption.value[0] = {
      label: '沟通结果',
      name: 'call_result',
      value: '',
      type: 'select',
      placeholder: '全部',
      fetchOptionApi: () => {
        return new Promise((resolve) => {
          resolve([
            {
              name: '全部',
              id: -1
            },
            {
              name: '已接通',
              id: 1
            },
            {
              name: '未接通',
              id: 2
            },
            {
              name: '挂断',
              id: 3
            },
            {
              name: '空号',
              id: 4
            },
            {
              name: '未联系',
              id: 0
            }
          ])
        })
      },
      formatOption: (v) => ({
        label: v.name,
        value: v.id
      })
    }
  }
  if (data.dis_rule && data.dis_rule == 2) {
    if (data.cycle_unit == 1) {
      searchOption.value[2] = {
        label: '执行周期',
        name: 'exec_cycle',
        value: [],
        type: 'datePicker',
        datePickerType: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        placeholder: '选择时间',
        popperClass: 'create_time'
      }
    } else {
      getCycle(data.task_id)
      console.log('data: ', data);
    }
  } else {
    searchOption.value[2] = {
      label: '执行周期',
      name: 'exec_cycle',
      value: [],
      type: 'datePicker',
      datePickerType: 'daterange',
      datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间',
      popperClass: 'create_time'
    }
  }
}
const getCycle = (data: any) => {
  const params = {
    task_id: data
  }
  searchOption.value[2] = {
    label: '执行周期',
    name: 'exec_cycle',
    value: '',
    type: 'select',
    placeholder: '请选择执行周期',
    fetchOptionApi: () => {
      return new Promise((resolve) => {
        execCyle(params).then((data: any) => {
          resolve(data)
        })
      })
    },
    formatOption: (v) => ({
      label: v.cycle_type == 2 ? `第${v.cycle_num}周 ${v.cycle_begin.split(' ')[0]}-${v.cycle_end.split(' ')[0]}` : `第${v.cycle_num}月  ${v.cycle_begin.split(' ')[0]}-${v.cycle_end.split(' ')[0]}`,
      value: [v.cycle_begin, v.cycle_end]
    })
  }
}
const search = (data: any) => {
  if (data && !Array.isArray(data.exec_cycle)) {
    data.exec_cycle = [data.exec_cycle, data.exec_cycle.split(' ')[0] + ' ' + '23:59:59']
  }
  const params = {
    ...defaultParams,
    task_id: state.searchParams.task_id,
    work_user_id: state.searchParams.work_user_id,
    ...data
  }
  state.searchParams = deepCopy(params)
}
const getData = () => {
  return workUserDetail
}
const reset = (v: any) => {
  defaultParams.task_id = state.searchParams.task_id
  defaultParams.work_user_id = state.searchParams.work_user_id
  state.searchParams = deepCopy(defaultParams)
}
const handleClose = () => {
  searchRef.value.reset()
}
defineExpose({
  openCust
})
</script>
<style lang="scss" scoped>
.scrollbar {
  height: calc(100vh - 400px);
  overflow-y: auto;
}
</style>
